import { useSearchParams } from "react-router-dom";
import "./talk.css"
import React, { useEffect, useState } from 'react';

export default function Talk() {
    const [title, setTitle] = useState('');
    const [content, setContent] = useState('');
    const [posts, setPosts] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const [searchParams] = useSearchParams();
    const currentEmail = searchParams.get('email'); 
    
    // 分页状态管理
    const [currentPage, setCurrentPage] = useState(1);
    const postsPerPage = 5; // 每页显示5条

    const deletePost = async (postId) => {
        try {
            const res = await fetch(`http://localhost:5000/api/post/delete/${postId}`, {
                method: 'DELETE', // 后端需支持DELETE请求
                headers: { 'Content-Type': 'application/json' },
                // 可传递当前用户邮箱用于后端二次校验（防止非法删除）
                body: JSON.stringify({ email: currentEmail })
            });
            
            if (!res.ok) throw new Error(`删除失败: ${res.status}`);
            return await res.text(); // 接收后端删除成功的反馈
        } catch (err) {
            console.error('删除帖子出错:', err);
            throw err;
        }
    };

    // 保存帖子到服务器（原有代码，无修改）
    const savePost = async (post) => {
        try {
            const res = await fetch(`http://localhost:5000/api/post/add`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(post)
            });
            
            if (!res.ok) throw new Error(`保存失败: ${res.status}`);
            return await res.text();
        } catch (err) {
            console.error('保存帖子出错:', err);
            throw err;
        }
    };

    // ---------------------- 新增：处理删除逻辑 ----------------------
    const handleDelete = async (postId, e) => {
        e.stopPropagation(); // 防止事件冒泡影响其他元素
        // 二次确认，避免误操作
        const confirmDelete = window.confirm('确定要删除这条帖子吗？删除后不可恢复！');
        if (!confirmDelete) return;
        
        setIsLoading(true);
        setError(null);
        
        try {
            await deletePost(postId); // 调用删除接口
            fetchPosts(); // 删除后重新加载帖子列表，更新UI
        } catch (err) {
            setError('删除失败，请稍后再试');
        } finally {
            setIsLoading(false);
        }
    };

    // 处理表单提交（原有代码，无修改）
    const handleSubmit = async (e) => {
        e.preventDefault();
        
        // 简单验证
        if (!title.trim() || !content.trim()) {
            alert('请输入标题和内容');
            return;
        }
        
        setIsLoading(true);
        setError(null);
        
        try {
            // 创建新帖子对象
            const newPost = {
                id: Date.now(),
                email: currentEmail, // 使用当前用户邮箱作为作者
                title,
                content,
                timestamp: new Date().toLocaleString()
            };
            
            await savePost(newPost);
            fetchPosts(); // 发布后重新加载列表
            // 清空表单
            setTitle('');
            setContent('');
        } catch (err) {
            setError('发布失败，请稍后再试');
        } finally {
            setIsLoading(false);
        }
    };

    // 加载所有帖子
    const fetchPosts = async () => {
        setIsLoading(true);
        setError(null);
        try {
            const res = await fetch("http://localhost:5000/api/post/all");
            if (!res.ok) throw new Error(`加载失败: ${res.status}`);
            
            const postsData = await res.json();
            
            const sortedPosts = [...postsData].sort((a, b) => 
                new Date(b.timestamp) - new Date(a.timestamp)
            );
            setPosts(sortedPosts);
            setCurrentPage(1); // 重置到第一页
        } catch (err) {
            setError('加载帖子失败，请刷新页面重试');
            console.log(err);
        } finally {
            setIsLoading(false);
        }
    };

    // 初始加载帖子
    useEffect(() => {
        fetchPosts();
    }, []);

    // 计算当前页显示的帖子
    const indexOfLastPost = currentPage * postsPerPage;
    const indexOfFirstPost = indexOfLastPost - postsPerPage;
    const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);

    // 计算总页数
    const totalPages = Math.ceil(posts.length / postsPerPage);

    // 页码切换
    const handlePageChange = (page) => {
        setCurrentPage(page);
        document.querySelector('.posts-list').scrollIntoView({ behavior: 'smooth' });
    };

    return (
        <section id="talk" className="talk-body">
            <div className="section-header">
                <h2 className="section-title">E起见证</h2>
                <p className="section-desc">
                    和世界各地的Edurance用户共同见证您的健身之旅
                </p>
            </div>
            
            {/* 帖子列表 */}
            <div className="posts-list">
                <h2>帖子列表</h2>
                
                {isLoading ? (
                    <p>加载中...</p>
                ) : posts.length === 0 ? (
                    <p className="no-posts">暂无帖子，快来发布第一条吧！</p>
                ) : (
                    <>
                        {currentPosts.map(post => (
                            <div key={post.id} className="post-item">
                                <h3 className="post-title">{post.title}</h3>
                                <h4>作者: {post.email}</h4>
                                <div className="post-meta">发布时间: {post.timestamp}</div>
                                <div className="post-content">{post.content}</div>
                                {currentEmail === post.email && (
                                    <button
                                        className="delete-button"
                                        onClick={(e) => handleDelete(post.id, e)}
                                        disabled={isLoading} // 加载中禁用按钮
                                    >
                                        {isLoading ? '删除中...' : '删除帖子'}
                                    </button>
                                )}
                            </div>
                        ))}
                        
                        {/* 分页控件 */}
                        {totalPages > 1 && (
                            <div className="pagination">
                                {[...Array(totalPages)].map((_, index) => (
                                    <button
                                        key={index + 1}
                                        className={`page-button ${currentPage === index + 1 ? 'active' : ''}`}
                                        onClick={() => handlePageChange(index + 1)}
                                    >
                                        {index + 1}
                                    </button>
                                ))}
                            </div>
                        )}
                    </>
                )}
            </div>
            
            {/* 发帖功能 */}
            <div className="post-container">
                {error && (
                    <div className="error-message" style={{ color: 'red', margin: '10px 0' }}>
                        {error}
                    </div>
                )}
                
                <form className="post-form" onSubmit={handleSubmit}>
                    <h2>发布新帖子</h2>
                    
                    <div className="form-group">
                        <label htmlFor="title">标题</label>
                        <input
                            type="text"
                            id="title"
                            className="title-input"
                            value={title}
                            onChange={(e) => setTitle(e.target.value)}
                            placeholder="请输入标题"
                            disabled={isLoading}
                        />
                    </div>
                    
                    <div className="form-group">
                        <label htmlFor="content">内容</label>
                        <textarea
                            id="content"
                            className="content-input"
                            rows="5"
                            value={content}
                            onChange={(e) => setContent(e.target.value)}
                            placeholder="请输入内容"
                            disabled={isLoading}
                        />
                    </div>
                    
                    <button 
                        type="submit" 
                        className="post-button"
                        disabled={isLoading}
                    >
                        {isLoading ? '发布中...' : '发布'}
                    </button>
                </form>
            </div>
        </section>
    );
}